package CodeTop;

public class Solution200 {
    int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};

    public int numIslands(char[][] grid) {
        int num = 0;
        for (int i = 0;i < grid.length;i++) {
            for (int j = 0;j < grid[0].length;j++) {
                if (grid[i][j] == '1') {
                    dfs(grid, i, j);
                    num++;
                }
            }
        }
        return num;
    }

    public void dfs (char[][] grid, int i, int j) {
        if (!isValid(grid, i, j) || grid[i][j] != '1') {
            return;
        }
        grid[i][j] = '2';
        for (int d = 0;d < 4;d++) {
            dfs(grid, i + dir[d][0], j + dir[d][1]);
        }
    }

    public boolean isValid (char[][] grid, int i, int j) {
        if (i >= 0 && i < grid.length && j >= 0 && j < grid[0].length) {
            return true;
        }
        return false;
    }
}
